package utils;
import java.io.*;
import java.util.*;

public class DateUtils
{
	private static File dateFile = new File(resource.Resource.getDateFilePath());
	private static Date date;
	
	public static void saveDate(Date d) throws FileNotFoundException
	{
		date = d;
		PrintWriter out = new PrintWriter(dateFile);
		out.println(date.getTime());
		out.println(date);
		out.close();		
	}
	
	public static Date getDate(){
		return date;
	}
	public static void loadDate() throws FileNotFoundException, IOException
	{
		 BufferedReader in = new BufferedReader(new FileReader(dateFile));
		 String line = in.readLine();
		 in.close();
		 date = new Date(Long.parseLong(line));
	}
	
	public static long getLongDate()
	{
		 return date.getTime();
	}
	
	public static boolean existsDate()
	{
		if (dateFile.exists()){
			BufferedReader in;
			try {
				in = new BufferedReader(new FileReader(dateFile));
				String line = in.readLine();
				in.close();
				Date d = new Date(Long.parseLong(line));
				Date now = new Date();
				if(d.after(now)){
					return true;
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(0);
			}
		}
		return false;
	}
	public static String getCountDownTo(Date date){
		GregorianCalendar diff = new GregorianCalendar();
		diff.setTimeInMillis(date.getTime() - System.currentTimeMillis());
		String countDownString = new String ("");
		int gg = diff.get(Calendar.DAY_OF_YEAR);
		int hh = diff.get(Calendar.HOUR_OF_DAY);
		int mm = diff.get(Calendar.MINUTE);
		if(gg != 0)
			if(gg == 1)
				countDownString += gg+" giorno ";
			else
				countDownString += gg+" giorni ";
		if(hh != 0)
			if(gg == 1)
				countDownString += hh+" ora ";
			else
				countDownString += hh+" ore ";
		if(mm != 0)
			if(gg == 1)
				countDownString += mm+" minuto ";
			else
				countDownString += mm+" minuti ";
		
		return countDownString;
	}
	public static String getCountDownHTML(Date date){
		GregorianCalendar diff = new GregorianCalendar();
		diff.setTimeInMillis(date.getTime() - System.currentTimeMillis());
		String countDownString = new String ("<HTML>");
		int gg = diff.get(Calendar.DAY_OF_YEAR);
		int hh = diff.get(Calendar.HOUR_OF_DAY);
		int mm = diff.get(Calendar.MINUTE);
		if(gg != 0)
			if(gg == 1)
				countDownString += "<B>"+gg+"</B> giorno ";
			else
				countDownString += "<B>"+gg+"</B> giorni ";
		if(hh != 0)
			if(hh == 1)
				countDownString += "<B>"+hh+"</B> ora ";
			else
				countDownString += "<B>"+hh+"</B> ore ";
		if(mm != 0)
			if(mm == 1)
				countDownString += "<B>"+mm+"</B> minuto ";
			else
				countDownString += "<B>"+mm+"</B> minuti ";
		
		return countDownString;
	}
	
}
